#!/usr/local/bin/perl -w

use App::Options (
    options => [qw(dbdriver dbclass dbhost dbname dbuser dbpass)],
    option => {
        dbclass  => { default => "App::Repository::MySQL", },
        dbdriver => { default => "mysql", },
        dbhost   => { default => "localhost", },
        dbname   => { default => "test", },
        dbuser   => { default => "", },
        dbpass   => { default => "", },
    },
);

use Test::More qw(no_plan);
use lib "../App-Context/lib";
use lib "../../App-Context/lib";
use lib "lib";
use lib "../lib";
use lib ".";
use lib "t";

use_ok("App");
use_ok("App::Repository");
use RepositoryTestUtils qw(create_table_test_person drop_table_test_person);
use strict;

if (!$App::options{dbuser}) {
    ok(1, "No dbuser given. Tests assumed OK. (add dbuser=xxx and dbpass=yyy to app.conf in 't' directory)");
    exit(0);
}

my $context = App->context(
    conf_file => "",
    conf => {
        Repository => {
            default => {
                class => $App::options{dbclass},
                dbdriver => $App::options{dbdriver},
                dbhost => $App::options{dbhost},
                dbname => $App::options{dbname},
                dbuser => $App::options{dbuser},
                dbpass => $App::options{dbpass},
                table => {
                    test_person => {
                        primary_key => ["person_id"],
                    },
                },
            },
        },
    },
    debug_sql => $App::options{debug_sql},
    trace => $App::options{trace},
);

# my $options= $context->{options};
# print "OPTIONS: {", join("|", %$options), "}\n";

my $rep = $context->repository();
&drop_table_test_person($rep);
&create_table_test_person($rep);

my $t_dir = "t";
$t_dir = "." if (! -d $t_dir);

{
    my $dbclass = $App::options{dbclass} || "mysql";
    if ($dbclass eq "oracle") {
        $rep->_load_rep_metadata();

        is($rep->insert_rows("test_person", ["age","first_name","gender","state"],
            [[39,"stephen",  "M","GA"],
             [37,"susan",    "F","GA"]]),2,
            "insert rows (2 rows, primary key included)");
        is($rep->get("test_person",1,"first_name"), "stephen", "1st row got in [stephen]");
        is($rep->get("test_person",2,"first_name"), "susan",   "2nd row got in [susan]");

        is($rep->import_rows("test_person", ["age","first_name","gender","state"],
            "$t_dir/files/DBI-import.01.dat", {field_sep => "|"}),
            120,
            "import from file [files/DBI-import.01.dat]");
        is($rep->get("test_person",3,"first_name"), "mike",    "3rd row got in [mike]");
        is($rep->get("test_person",4,"first_name"), "mary",    "4th row got in [mary]");
        is($rep->get("test_person",5,"first_name"), "maxwell", "5th row got in [maxwell]");
        is($rep->get("test_person",6,"first_name"), "myrtle",  "6th row got in [myrtle]");
    }
    else {
        ok(1, "These tests are only for Oracle");
    }
}

